package com.bangcommunity.bbframe.mybatis.manager;

import com.bangcommunity.bbframe.common.base.PageBean;
import com.bangcommunity.bbframe.common.base.PageInfo;
import com.bangcommunity.bbframe.common.exception.ValidateUtil;
import com.bangcommunity.bbframe.mybatis.criteria.AbstractorCriteria;
import com.bangcommunity.bbframe.mybatis.mapper.BaseMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.io.Serializable;
import java.util.List;

/**
 * 业务操作基类
 * 
 * @author tanghc
 */
public class BaseService<PK extends Serializable, E extends Serializable, C extends AbstractorCriteria, D extends BaseMapper<PK, E, C>, M extends IBaseManager<PK, E, C>>
        implements IBaseService<PK, E, C> {
    protected Logger logger = LoggerFactory.getLogger(this.getClass());
    protected M baseManager;

    @Autowired
    protected void setBaseDao(M baseManager) {
        this.baseManager = baseManager;
    }

    @Override
    public int countByExample(C example) {
        ValidateUtil.checkNotNull(example, "条件不能为空");
        return this.baseManager.countByExample(example);
    }

    @Override
    public void deleteByPrimaryKey(PK id) {
        ValidateUtil.checkNotNull(id, "数据id不能为空");
        this.baseManager.deleteByPrimaryKey(id);
    }

    @Override
    public void insert(E record) {
        ValidateUtil.checkNotNull(record, "删除数据不能为空");
        this.baseManager.insert(record);
    }

    @Override
    public List<E> selectByExample(C example) {
        ValidateUtil.checkNotNull(example, "条件不能为空");
        return this.baseManager.selectByExample(example);
    }

    @Override
    public E selectByPrimaryKey(PK id) {
        ValidateUtil.checkNotNull(id, "条件不能为空");
        return this.baseManager.selectByPrimaryKey(id);
    }

    @Override
    public PageBean<E> page(C example) {
        ValidateUtil.checkNotNull(example, "条件不能为空");
        if (null != example.getOffSet() && null != example.getPageSize()) {
            PageInfo pageInfo = PageInfo.fromOffsetAndSize(example.getOffSet(), example.getPageSize());
            return new PageBean<>(pageInfo.getPageNo(), example.getPageSize(), this.selectByExample(example),
                    this.countByExample(example));
        }
        return new PageBean<>(this.selectByExample(example), this.countByExample(example));
    }

    @Override
    public void updateByPrimaryKeySelective(E record) {
        ValidateUtil.checkNotNull(record, "更新数据不能为空");
        this.baseManager.updateByPrimaryKeySelective(record);
    }
}
